const router = require('koa-router')();

const User = require('../model/user')

/**
 * 注册接口
 */
router.post('/logon', async (context, next) => {
    let body = context.request.body

    context.verifyParams({
        phone:{
            type: 'string',
            required: true
        },
        passWord:{
            type: 'string',
            required: true
        },
        nickName:{
            type: 'string',
            required: true
        }
    })
    const hasPhone = await User.find({phone: body.phone})
    const hasName = await User.find({nickName: body.nickName})
    if(hasPhone.length > 0){
        context.throw(412, '手机号已注册')
    }else if(hasName.length > 0){
        context.throw(412, '用户名已经被占用')
    }else { 
        body.token = parseInt(Math.random() * 1e20).toString(16)
        await new User(body).save() 

        const users = await User.find({phone: body.phone})
        const user = {
            phone: users[0].phone,
            nickName: users[0].nickName,
            token: users[0].token
        }
        context.response.body = user
    }

    await next()
})
/**
 * 登录接口
 * 入参:{
            userName:'',//用户名
            password:''//密码
        }
    出参:{
            token:''//登录验证标识
        }
 * 
 */
router.post('/login', async (context, next)=>{
    let body = context.request.body

    context.verifyParams({
        phone:{
            type: 'string',
            required: true
        },
        passWord:{
            type: 'string',
            required: true
        }
    })
    const users = await User.find({phone: body.phone, passWord: body.passWord })
    if(users.length > 0) {
        context.response.body = {
            token: users[0].token,
            nickName: users[0].nickName
         }
    }else {
        context.throw(401, "用户名或密码错误")
    }
    next()
})

module.exports = router